/**
 * 
 */
package org.rico.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.rico.server.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author rico
 *
 */
public class LoginServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(LoginServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String systemId = req.getParameter("systemId");
		String backUrl = req.getParameter("backUrl");
		
		HttpSession session = req.getSession();
		logger.info("###sessionId = {}", session.getId());
		
		boolean isLogin = false;
		if(session.getAttribute("isLogin") != null) {
			isLogin = (boolean) session.getAttribute("isLogin");
		}
		logger.info("LoginServlet.doPost[systemId = {}, isLogin={}]", systemId, isLogin);
		
		if(isLogin) {
			String token = CacheManager.get(systemId).getToken();
			resp.sendRedirect(backUrl.concat("?token=").concat(token));
			
		} else {
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		}
	}
	
}
